<template>
	<view>
		<u-upload 
		ref="upload"
		:action="action" 
		:max-size="5 * 1024 * 1024" max-count="1"
		:before-upload="beforeUpload"
		:custom-btn="true"
		:form-data="formData"
		:show-progress="false"
		:multiple="false"
		:deletable="false"
		:show-upload-list="true"
		width="0"
		height="0"
		@on-success="onSuccess"
		>
		<u-avatar slot="addBtn" :src="vuex_user.avatar_url" size="140"></u-avatar>
		</u-upload>
	</view>
</template>

<script>
	let _this={}
	export default {
		name: "oss-upload",
		data() {
			return {
				action: 'http:/laravel_shop_api.luwnto.oss-cn-beijing.aliyuncs.com/',
				formData:{},
				upFilename:""
			};
		},
		created() {
			_this=this;
		},
		methods: {
			async beforeUpload(index, list) {
				console.log(list);
				const {file}=list[0];
				//#ifdef H5
				const filename=file.name;
				//#endif
				//#ifndef H5
				const filename=file.path;
				//#endif
				// console.log(filename);
				
				//请求API，获取oss tokeen
				const ossToken=await _this.$u.api.authOssToken();
				console.log(ossToken);
				
				//设置上传域名
				_this.action=ossToken.host;
				
				//处理唯一文件名
				const suffix=filename.slice(filename.lastIndexOf('.'));
				// console.log(suffix);
				const upFilename=_this.$u.guid(20)+suffix;
				console.log(upFilename);
				_this.upFilename=upFilename;
				
				//额外的上传数据
				_this.formData={
					'key':upFilename,//上传后的文件名
					'policy':ossToken.policy,
					'OSSAccessKeyId':ossToken.accessid,
					'success_action_status' : '200',
					'signature': ossToken.signature,
				}
				return true;
			},
			async onSuccess(){//上传成功之后
				this.$refs.upload.remove(0);
				//请求API更新头像
				// console.log(this.upFilename)
				// console.log({avatar:this.upFilename});
				await this.$u.api.userAvatar({avatar:this.upFilename});
				this.$u.toast('更新成功');
				//更新缓存的用户信息
				this.$u.utils.updataUser();
			}
		},
		
	}
</script>

<style>

</style>
